//! 历史记录

use crate::consts::*;
use crate::net::Packet;
use core::num::Wrapping;
use heapless::HistoryBuffer;
use spin::Lazy;
use spin::RwLock;

static HISTORY: Lazy<RwLock<HistoryBuffer<Log, HistoryLen>>> =
    Lazy::new(|| RwLock::new(HistoryBuffer::new()));

/// 记录
#[derive(Default, PartialEq, Clone)]
struct Log {
    src: u16,
    dst: u16,
    sn: u8,
    data_sum: Wrapping<u8>,
    data_crc: u16,
}

fn data2log(packet: &Packet) -> Log {
    Log {
        src: crc16::State::<crc16::MODBUS>::calculate(&packet.src),
        dst: crc16::State::<crc16::MODBUS>::calculate(&packet.dst),
        sn: packet.sn,
        data_sum: packet.data.iter().map(|n| Wrapping(*n)).sum(),
        data_crc: crc16::State::<crc16::MODBUS>::calculate(&packet.data),
    }
}
/// 添加记录
pub(crate) fn add(packet: &Packet) {
    HISTORY.write().write(data2log(packet));
}
/// 查历史记录
pub(crate) fn has(packet: &Packet) -> bool {
    let new_log = data2log(packet);
    HISTORY.read().as_slice().contains(&new_log)
}
